from django.http import HttpResponse, HttpResponseRedirect
from django.template import Template, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
import logging

from contacts.models import *
from contacts.forms import *
from contacts.views_obsolete import insert_contact_type

logger = logging.getLogger("django")


@login_required
def select_records(request, model, redirect, template):
    record_list = model.objects.all()
    return render_to_response(template, {'item_list': record_list, 'redirect': redirect})


@login_required
def new_record(request, form, redirect, template):
    if request.method == 'POST' and request.POST.get('Cancel', ''):
        return HttpResponseRedirect(redirect)
    if request.method == 'POST' and request.POST.get('Submit', ''):
        #
        # Request is from our submit button. Store the record.
        #
        form = form(request.POST)
        if form.is_valid():
            logger.debug("Form is valid")
            form.save()
            return HttpResponseRedirect(redirect)
        else:
            logger.debug("Form is not valid")
    else:
        form = form
    return render_to_response(template, {'form': form})
    
   
@login_required
def edit_record(request, id, model, form, redirect, template):
    if request.method == 'POST' and request.POST.get('Cancel', ''):
        return HttpResponseRedirect(redirect)
    if request.method == 'POST' and request.POST.get('Submit', ''):
        #
        # Request is from our submit button. Store the record.
        #
        r = model.objects.get(id=id)
        form = form(request.POST, instance=r)
        if form.is_valid():
            logger.debug("Form is valid")
            form.save()
            return HttpResponseRedirect(redirect)
        else:
            logger.debug("Form is not valid")
    else:
        r = model.objects.get(id=id)
        form = form(instance=r)
    return render_to_response(template, {'form': form, 'id': id})
    

@login_required
def del_records(request, model, redirect):
    list = request.POST.getlist('checkbox')
    logger.debug(str(list))
    for e in list:
        ct = model.objects.get(id=e)
        ct.delete()
    return HttpResponseRedirect(redirect)
    

@login_required
def edit_parent(request, id, model, form, redirect, template, child_model, child_template):
    if request.method == 'POST' and request.POST.get('Cancel', ''):
        return HttpResponseRedirect(redirect)
    if request.method == 'POST' and request.POST.get('Submit', ''):
        #
        # Request is from our submit button. Store the record.
        #
        person = model.objects.get(id=id)
        form = form(request.POST, instance=person)
        if form.is_valid():
            logger.debug("Form is valid")
            form.save()
            return HttpResponseRedirect(redirect)
        else:
            logger.debug("Form is not valid")
    else:
        r = model.objects.get(id=id)
        form = form(instance=r)
        method_name = "%s_set" % child_model.__name__.lower()
        children = getattr(r, "%s_set" % child_model.__name__.lower()).all()
    return render_to_response(template, {'form': form, 'id': id, 'children_list': children, 'child_template': child_template})
    

@login_required
def del_child(request, parent_id, model, redirect):
    list = request.POST.getlist('checkbox')
    logger.debug(str(list))
    for e in list:
        c = model.objects.get(id=e)
        c.delete()
    return HttpResponseRedirect("%s%s/" % (redirect, parent_id))
    

@login_required
def new_child(request, parent_id, parent_model, model, foreign, form, redirect, template):
    if request.method == 'POST' and request.POST.get('Cancel', ''):
        return HttpResponseRedirect('/select-contact/')
    p = parent_model.objects.get(id=parent_id)
    #exec "r=model(%s=p)" % foreign 
    r = model(**{foreign: p})
    if request.method == 'POST' and request.POST.get('Submit', ''):
        #
        # Request is from our submit button. Store the record.
        #
        form = form(request.POST, instance=r)
        if form.is_valid():
            logger.debug("Form is valid")
            form.save()
            return HttpResponseRedirect('%s%s/' % (redirect, parent_id))
        else:
            logger.debug("Form is not valid")
    else:
        #
        # GET
        #
        form = form(instance=r)
    return render_to_response(template, {'form': form})
    

@login_required
def edit_child(request, parent_id, id, parent_model, model, form, redirect, template):
    if request.method == 'POST' and request.POST.get('Cancel', ''):
        return HttpResponseRedirect('/select-contact/')
    p = parent_model.objects.get(id=parent_id)
    r = model.objects.get(id=id)
    if request.method == 'POST' and request.POST.get('Submit', ''):
        #
        # Request is from our submit button. Store the record.
        #
        form = form(request.POST, instance=r)
        if form.is_valid():
            logger.debug("Form is valid")
            form.save()
            return HttpResponseRedirect('%s%s/' % (redirect, parent_id))
        else:
            logger.debug("Form is not valid")
    else:
        form = form(instance=r)
    return render_to_response(template, {'form': form, 'parent': p})
    

@login_required
def main_page(request):
    return render_to_response('main-page.html', context_instance=RequestContext(request))
    
    
